
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import {
  PageContainer,
  ProTable,
} from '@ant-design/pro-components';
import React, { useRef, useState } from 'react';

import { history, useModel } from 'umi';
//services

import { listSongByPageUsingGet } from '@/services/music-recommend/songController';
import { CaretRightOutlined, PlayCircleOutlined, PlusOutlined } from '@ant-design/icons';




const SearchPage: React.FC = () => {
  

  // const [showDetail, setShowDetail] = useState<boolean>(false);
  // const [currentRow, setCurrentRow] = useState<API.SongVO>();
  // const [selectedRows, setSelectedRows] = useState<API.SongVO[]>([]);
  const {
    first,
    songs,AddSong,
    setPlaying,
    setCurrentSong,
    setCurrentSongIndex,
  } = useModel('musicPlayerModel');

  const actionRef = useRef<ActionType>();
  const columns: ProColumns<API.SongVO>[] = [
    // {
    //   title: 'ID',
    //   dataIndex: 'id',
    //   // sorter: true,
    //   hideInForm: true,
    //   renderText: (val: string) =>
    //     `${val}`,
    // },
    //TODO:
    // {
    //   // title: "图片",
    //   dataIndex: 'picture',
    //   render: (dom, entity) => {
    //     return (
    //       <a
    //         onClick={() => {
    //           setCurrentRow(entity);
    //           setShowDetail(true);
    //         }}
    //       >
    //         {dom}
    //       </a>
    //     );
    //   },
    // },
    
    {
      title: '标题',
      dataIndex: 'name',
      // sorter: true,
      hideInForm: true,
      align:'center',
      render: (_, record) => [
        <a
          key="song_detail"
          onClick={() => {
            // 跳转
            history.push(`/song?id=${record.id}`);
          }}
        >
          <span>{record.name}</span>
        </a>,       
      ],
    },
    {
      title: '歌手',
      dataIndex: 'singerName',
      // sorter: true,
      hideInForm: true,
      align:'center',
      renderText: (val: string) =>
        `${val}`,
    },
    {
      title: 'tags',
      dataIndex: 'tags',
      align:'center'
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      align:'center',
      render: (_, record) => (
        <div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center' }}>
          <a
            key="play"
            onClick={() => {
              handlePlay(record);
            }}
            
          >
            <PlayCircleOutlined />
            {/* <CaretRightOutlined /> */}
          </a>
          <a
            key="add"
            onClick={() => {
              handleAdd(record);
            }}
            style={{ marginLeft: 8 }} // 为两个链接添加间距
          >
            <PlusOutlined />
          </a>
          
          
        </div>
      ),
    },
  ];


  // const handleSearch = async (value:string) =>{
  //   try{
  //     const respond = await searchSongByPageUsingGet({text:value});
  //     if(respond.code==0 && respond.data?.records) {
  //       setMyDataSource(respond.data?.records);
  //     }

  //   } catch(error) {
  //     message.error('搜索失败，请重试！');
  //   }
  // }


  

  const handleAdd = async (clickedRow:API.SongVO) =>{
    if(!clickedRow) return;
    // alert(clickedRow.url);
    AddSong(clickedRow);
    if(first) {
      setPlaying(true);
    }
  }

  const handlePlay = async (clickedRow:API.SongVO) =>{
    if(!clickedRow) return;
    //check is in songs list
    const index = songs.findIndex(item => item.id==clickedRow.id)
    if(index != -1) {
      setCurrentSong(clickedRow);
      setCurrentSongIndex(index);
    } else {
      const nextIndex = songs.length;
      AddSong(clickedRow);
      setCurrentSong(clickedRow);
      setCurrentSongIndex(nextIndex);
    }
    setPlaying(true);

  }
  

  return (    
    <PageContainer
      title= ' '
    >
      <ProTable<API.SongVO, API.listSongByPageUsingGETParams>
        // ghost
        headerTitle={''}
        actionRef={actionRef}
        rowKey="id"

        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => [
          // <Button
          //   type="primary"
          //   key="primary"
          //   onClick={() => {
          //     handleCreateModalOpen(true);
          //   }}
          // >
          //   <PlusOutlined /> <span>New</span>
          // </Button>,
        ]}
        
        
        request={async(params,sort,filter,)=>{
            const msg =await listSongByPageUsingGet({
              ...params
            });
            return {
              data: msg.data?.records,
              success: msg.code==0,
              total: msg.data?.total,
            };
        }}

        columns={columns}

        // 多选复选框
        // rowSelection={{
        //   onChange: (_, selectedRows) => {
        //     setSelectedRows(selectedRows);
        //   },
        // }}

      />

      {/* 多选操作批量删除 */}
      {/*selectedRows?.length > 0 && (
        <FooterToolbar
          extra={
            <div>
              <span>已选择</span>{' '}
              <a style={{ fontWeight: 600 }}>{selectedRowsState.length}</a>{' '}
              <span>项</span>
              &nbsp;&nbsp;
            </div>
          }
        >
          <Button type='primary'
            onClick={async () => {
              await handleRemove(selectedRowsState);
              setSelectedRows([]);
              actionRef.current?.reloadAndRest?.();
            }}
          >
            <span>批量删除</span>
          </Button>
          
        </FooterToolbar>
      )} */}

      {/* 模态窗口 新建表单*/}
      {/* <ModalForm
        title={'新建试卷'}
        width="400px"
        open={createModalOpen}
        onOpenChange={handleCreateModalOpen}
        onFinish={async (value) => {
          const success = await handleAdd(value as API.Paper);
          if (success) {
            handleCreateModalOpen(false);
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
      >
        <ProFormText
          rules={[
            {
              required: true,
              message: '试卷名称是必填项',
            },
          ]}
          width="md"
          name="name"
        />
      </ModalForm> */}
      
      {/* Drawer：屏幕边缘滑出的侧滑面板 ，showDetail */}
      {/* <Drawer
        width={600}
        open={showDetail}
        onClose={() => {
          setCurrentRow(undefined);
          setShowDetail(false);
        }}
        closable={false}
      >
        {currentRow?.name && (
          <ProDescriptions<API.SongVO>
            column={2}
            title={currentRow?.name}
            request={async () => ({
              data: currentRow || {},
            })}
            params={{
              id: currentRow?.name,
            }}
            columns={columns as ProDescriptionsItemProps<API.SongVO>[]}
          />
        )}
      </Drawer> */}


    </PageContainer>
  
  );
};

export default SearchPage;
